<template>
  <div class="editForm-wrapper">
    <el-dialog
      v-if="method === 'add' || 'edit'"
      width="520px"
      :title="title"
      :close-on-click-modal="false"
      v-dialogDrag
      :visible.sync="visible"
    >
      <el-form label-width="95px"  :model="inputForm" :rules="rules" ref="inputForm">
        <el-form-item label="业务流程:"  prop="modularId"
                      :rules="[{ required: true, message: '请选择业务流程', trigger: 'blur' }]">
          <el-select clearable v-model="inputForm.modularId" :disabled="disabledState===1" @change="getTypeByModularId(inputForm.modularId)" placeholder="请选择业务流程" >
            <el-option
              v-for="item in selectData"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="业务类型:"  prop="busType"
                      :rules="[{ required: true, message: '请选择业务类型', trigger: 'blur' }]">
          <el-select clearable :disabled="disabledState===1" v-model="inputForm.busType" >
            <el-option
              v-for="item in $dictUtils.getDictList(typeData)"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="业务模型:" prop="consoleModelId"
                      :rules="[{ required: true, message: '请选择业务模型', trigger: 'blur' }]">
          <el-select clearable v-model="inputForm.consoleModelId" >
            <el-option
              v-for="item in selectModelData"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="业务描述:" prop="describes">
          <el-input type="textarea"  v-model="inputForm.describes" placeholder="描述" ></el-input>
        </el-form-item>
        <el-form-item label="选择图标:" class="imageUploader">
          <el-upload
            class="avatar-uploader"
            :action="`${this.$http.BASE_URL}/model/iconUpload?oleImgId=`+inputForm.iconId"
            :headers="{token: $cookie.get('token')}"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :show-file-list="false">
            <img v-if="inputForm.iconPath" :src="inputForm.iconPath" class="avatar">
              <div v-if="inputForm.iconPath"  class="delBut">
                  <img src="~@/assets/img/del.png" @click.stop="delImage('iconPath')" alt="" style="height:15px">
              </div>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
            <span class="note">从本地上传（建议大小32*32像素）</span>
        </el-form-item>
      </el-form>
      <!-- <section class="hint-container">*注意：名称和数据规则为必填项，保存时需进行校验</section> -->
      <span slot="footer" class="dialog-footer">
        <el-button size="small" v-if="method != 'view'" type="primary" @click="doSubmit()" v-noMoreClick>确定</el-button>
        <el-button size="small" @click="visible = false">取消</el-button>
      </span>
    </el-dialog>

  </div>

</template>

<script>
import {saveModel, getAllSelectModular, getTypeByModularId, getModelInfo} from '@/api/model/model.js'
export default {
  data () {
    return {
      changeFlag: false,
      visible: false,
      loading: false,
      selectData: [],
      typeData: '',
      selectModelData: [],
      selectedOption: {},
      method: '',
      tenantId: '773481232943165456',
      title: '新增',
      disabledState:0,
      oldConsoleModelId:'',
      inputForm: {
        iconId: '',
        iconPath: '',
        id: '',
        state:0,
        busType: '',
        modularId: '',
        consoleModelId: '',
        processType: '',
        modularName: ''
      },
      value1:'',
      rules: {
        names: [{ required: true, message: '模型名称不能为空', trigger: 'blur' }],
        version: [{ required: true, message: '模型版本号不能为空', trigger: 'blur' }],
        describes: [{ required: true, message: '模型描述不能为空', trigger: 'blur' }]
      }
    }
  },
  watch: {
    value1(var1,var2){
      console.log(var1)
      this.getTypeByModularId(var1)
    }
  },
  methods: {
  	handleClose(done) {
		this.$Msg.confirm({
			title:'您确定要关闭吗？',
			content:this.GLOBAL.FORM_CLOSE_TIPS,
			confirmCall:()=>{
				done();
			}
		})
	},
      // 删除图片
      delImage (name) {
          this.inputForm[name] = ''
      },
    handleAvatarSuccess (res, file) {
      this.inputForm.iconId = res.result.id
      this.inputForm.iconPath = res.result.filePath
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type.indexOf('image/') >= 0
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isJPG) {
        this.$message.error('上传只能是图片格式!')
        return false
      }
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 5MB!')
        return false
      }
      return true
    },
    init (method, obj, prams) {

      this.getSelectList()
      this.method = method
      this.inputForm = obj
      console.log(obj)
      if (method === 'add') {
        this.title = '新增业务类型'
        this.visible = true
        this.inputForm = {
          iconImageId: '',
          iconPath: '',
          id: '',
          state:0,
          busType: '',
          modularId: '',
          consoleModelId: '',
          processType: '',
          modularName: ''
        }
        this.disabledState = 0
      } else if (method === 'edit') {
        this.title = '修改业务类型'
        this.visible = true
        getModelInfo({
          id: obj.id
        }).then((res) => {
          if (res.data.code === '200') {
            this.inputForm = res.data.result
            this.oldConsoleModelId = this.inputForm.consoleModelId
            this.value1 = res.data.result.modularId
            this.typeData = res.data.result.busValue
            this.disabledState = this.inputForm.state
          }
        })
      }
    },
    // 表单提交
    doSubmit () {
        if (this.oldConsoleModelId) {
            if (this.oldConsoleModelId !== this.inputForm.consoleModelId) {
                this.$confirm('是否替换原有业务中的设置？', {
                    distinguishCancelAndClose: true,
                    confirmButtonText: '替换',
                    cancelButtonText: '不替换',
                    type: 'warning'
                }).then(() => {
                    this.$set(this.inputForm, 'modelChangeFlag', true)
                    this.$refs['inputForm'].validate((valid) => {
                        if (valid) {
                            this.loading = true
                            saveModel(this.inputForm).then(res => {
                                if (res.data.code === '200') {
                                    this.$message({
                                        message: '操作成功',
                                        type: 'success',
                                        duration: 1500
                                    })
                                    this.visible = false
                                    this.$emit('refresh')
                                }
                            })
                        }
                    })
                }).catch(action => {
                    // 判断是 cancel (自定义的取消) 还是 close （关闭弹窗）
                    if (action === 'cancel') {
                        this.$set(this.inputForm, 'modelChangeFlag', false)
                        this.$refs['inputForm'].validate((valid) => {
                            if (valid) {
                                this.loading = true
                                saveModel(this.inputForm).then(res => {
                                    if (res.data.code === '200') {
                                        this.$message({
                                            message: '操作成功',
                                            type: 'success',
                                            duration: 1500
                                        })
                                        this.visible = false
                                        this.$emit('refresh')
                                    }
                                })
                            }
                        })
                    }
                });
            }
        } else {
            this.$set(this.inputForm, 'modelChangeFlag', false)
            this.$refs['inputForm'].validate((valid) => {
                if (valid) {
                    this.loading = true
                    saveModel(this.inputForm).then(res => {
                        if (res.data.code === '200') {
                            this.$message({
                                message: '操作成功',
                                type: 'success',
                                duration: 1500
                            })
                            this.visible = false
                            this.$emit('refresh')
                        }
                    })
                }
            })
        }

    },
    getSelectList () {
      getAllSelectModular({}).then((res) => {
        if (res.data.code === '200') {
          this.selectData = res.data.result
        }
      })
    },
    getTypeByModularId (modularId) {
      this.value1 = modularId
      getTypeByModularId({
        modularId: modularId
      }).then((res) => {
        if (res.data.code === '200') {
          this.typeData = res.data.result.typeVo.value
          this.selectModelData = res.data.result.modelVo
          console.log(this.typeData)
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
  .hint-container{
    width: 393px;
    height: 11px;
    font-size: 12px;
    font-weight: 400;
    color: #FF1F1F;

  }
    .editForm-wrapper{
        ::v-deep .el-dialog{
            .el-form{
                .el-textarea__inner{
                    width: 320px;
                }
                .note{
                    color: #FF3E3E;
                    font-size: 12px;
                }
            }
        }
    }
</style>
